<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="老人姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单人" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <br/>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in lekang_orderstatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="交易状态" prop="transactionStatus">
        <el-select v-model="queryParams.transactionStatus" placeholder="请选择交易状态" clearable>
          <el-option
            v-for="dict in dictionarytype"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="逻辑删除" prop="isDeleted">
        <el-input
          v-model="queryParams.isDeleted"
          placeholder="请输入逻辑删除"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="额外字段1" prop="extraField1">
        <el-input
          v-model="queryParams.extraField1"
          placeholder="请输入额外字段1"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="额外字段2" prop="extraField2">
        <el-input
          v-model="queryParams.extraField2"
          placeholder="请输入额外字段2"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 订单状态筛选 -->
    <div class="status-filter">
      <el-radio-group v-model="queryParams.orderStatus" size="large" @change="handleQuery">
        <el-radio-button :label="null">全部</el-radio-button>
        <el-radio-button 
          v-for="dict in lekang_orderstatus" 
          :key="dict.value" 
          :label="dict.value"
        >{{ dict.label }}</el-radio-button>
      </el-radio-group>
    </div>
    
    <hr/>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:ordermanagement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:ordermanagement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:ordermanagement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:ordermanagement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordermanagementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
<el-table-column label="老人姓名" align="center" prop="elderly.name" />
<el-table-column label="床位号" align="center" prop="bed.bedNo" />
<el-table-column label="护理项目名称" align="center" prop="nursingItem.name" />
<!-- <el-table-column label="订单编号" align="center" prop="orderNo" /> -->
 
      <el-table-column label="订单金额" align="center" prop="orderAmount" />
      <el-table-column label="期望服务时间" align="center" prop="expectedServiceTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedServiceTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单人" align="center" prop="familyMember.name" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="lekang_orderstatus" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="交易状态" align="center" prop="transactionStatus">
        <template #default="scope">
          <dict-tag :options="dictionarytype" :value="scope.row.transactionStatus"/>
        </template>
      </el-table-column>
     
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 根据订单状态动态控制按钮状态 -->
          <div style="display: flex; gap: 8px; flex-wrap: nowrap;">
            <el-button 
              link 
              type="primary" 
              @click="openCancelDialog(scope.row)" 
              :disabled="!canCancel(scope.row.orderStatus)"
            >取消</el-button>
            <el-button 
              link 
              type="primary" 
              @click="openRefundDialog(scope.row)" 
              :disabled="!canRefund(scope.row.orderStatus)"
            >退款</el-button>
            <el-button 
              link 
              type="primary" 
              @click="handlePreview(scope.row)" 
            >查看</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 取消订单对话框 -->
    <el-dialog title="填写取消原因" v-model="cancelDialogVisible" width="600px" append-to-body class="cancel-dialog">
      <el-form ref="cancelRef" :model="cancelForm" :rules="cancelRules" label-width="100px">
        <el-form-item label="取消原因" prop="reason">
          <el-select v-model="cancelForm.reason" placeholder="请选择" clearable style="width: 360px;">
            <el-option v-for="opt in cancelReasonOptions" :key="opt" :label="opt" :value="opt" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCancel">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog title="填写退款原因" v-model="refundDialogVisible" width="600px" append-to-body>
      <el-form ref="refundRef" :model="refundForm" :rules="refundRules" label-width="100px">
        <el-form-item label="退款原因" prop="reason">
          <el-input v-model="refundForm.reason" type="textarea" :maxlength="100" show-word-limit placeholder="请输入" style="width: 420px;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRefund">确定</el-button>
        </div>
      </template>
    </el-dialog>

    

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordermanagementRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="老人外键" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人外键" />
        </el-form-item>
        <el-form-item label="护理项目外键" prop="nursingItemId">
          <el-input v-model="form.nursingItemId" placeholder="请输入护理项目外键" />
        </el-form-item>
        <el-form-item label="订单金额" prop="orderAmount">
          <el-input v-model="form.orderAmount" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item label="期望服务时间" prop="expectedServiceTime">
          <el-date-picker clearable
            v-model="form.expectedServiceTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择期望服务时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下单人外键" prop="orderUserId">
          <el-input v-model="form.orderUserId" placeholder="请输入下单人外键" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-radio-group v-model="form.orderStatus">
            <el-radio
              v-for="dict in lekang_orderstatus"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="交易状态" prop="transactionStatus">
          <el-radio-group v-model="form.transactionStatus">
            <el-radio
              v-for="dict in dictionarytype"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="取消原因" prop="cancelReason">
          <el-input v-model="form.cancelReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="逻辑删除" prop="isDeleted">
          <el-input v-model="form.isDeleted" placeholder="请输入逻辑删除" />
        </el-form-item>
        <el-form-item label="额外字段1" prop="extraField1">
          <el-input v-model="form.extraField1" placeholder="请输入额外字段1" />
        </el-form-item>
        <el-form-item label="额外字段2" prop="extraField2">
          <el-input v-model="form.extraField2" placeholder="请输入额外字段2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Ordermanagement">
import { listOrdermanagement, getOrdermanagement, delOrdermanagement, addOrdermanagement, updateOrdermanagement } from "@/api/system/ordermanagement"
import { addRecordservice } from "@/api/system/recordservice"
import { listBalance, updateBalance } from "@/api/system/balance"

const { proxy } = getCurrentInstance()
const { lekang_orderstatus, dictionarytype } = proxy.useDict('lekang_orderstatus', 'dictionarytype')

const ordermanagementList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    elderlyId: null,
    orderUserId: null,
    createTime: null,
    orderStatus: null,
    transactionStatus: null,
    cancelReason: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null,
    name: null,
    nickname: null,
  },
  rules: {
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 查看进度（预览）
// 查看页跳转

// 取消对话框相关
const cancelDialogVisible = ref(false)
const cancelForm = ref({ reason: '' })
const cancelRules = { reason: [{ required: true, message: '请选择取消原因', trigger: 'change' }] }
const cancelReasonOptions = [
  '下错单',
  '价格原因',
  '服务不满意',
  '信息填写有误',
  '其他'
]
let cancelTargetId = null

// 退款对话框相关
const refundDialogVisible = ref(false)
const refundForm = ref({ reason: '' })
const refundRules = { reason: [{ required: true, message: '请输入退款原因', trigger: 'blur' }] }
let refundTargetRow = null

/** 查询订单管理列表 */
function getList() {
  loading.value = true
  listOrdermanagement(queryParams.value).then(response => {
    ordermanagementList.value = response.rows
    total.value = response.total
    loading.value = false
    console.log(response);
    
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    elderlyId: null,
    nursingItemId: null,
    orderAmount: null,
    expectedServiceTime: null,
    orderUserId: null,
    createTime: null,
    updateTime: null,
    remark: null,
    orderStatus: null,
    transactionStatus: null,
    cancelReason: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("ordermanagementRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订单管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrdermanagement(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改订单管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordermanagementRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrdermanagement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrdermanagement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除订单管理编号为"' + _ids + '"的数据项？').then(function() {
    return delOrdermanagement(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/ordermanagement/export', {
    ...queryParams.value
  }, `ordermanagement_${new Date().getTime()}.xlsx`)
}

/** 查看：打开进度弹窗并根据状态定位步骤 */
function handlePreview(row) {
  // 将当前行数据存入 sessionStorage 并跳转到全屏详情页
  sessionStorage.setItem('ordermanagement_preview', JSON.stringify(row || {}))
  proxy.$router.push({ path: '/order/preview' })
}

/** 打开取消对话框 */
function openCancelDialog(row) {
  cancelTargetId = row.id
  cancelForm.value = { reason: '' }
  cancelDialogVisible.value = true
}

/** 提交取消 */
function submitCancel() {
  proxy.$refs["cancelRef"].validate(valid => {
    if (!valid) return
    const payload = {
      id: cancelTargetId,
      cancelReason: cancelForm.value.reason,
      orderStatus: '已关闭',
      transactionStatus: '已关闭'
    }
    updateOrdermanagement(payload).then(() => {
      proxy.$modal.msgSuccess('取消成功')
      cancelDialogVisible.value = false
      getList()
    })
  })
}

/** 打开退款对话框 */
function openRefundDialog(row) {
  refundTargetRow = row
  refundForm.value = { reason: '' }
  refundDialogVisible.value = true
}

/** 提交退款（携带退款原因） */
async function submitRefund() {
  const valid = await proxy.$refs["refundRef"].validate().catch(() => false)
  if (!valid) return
  
  try {
    // 生成退款编号：RF + 4位随机数字
    const refundNo = 'RF' + Math.floor(Math.random() * 10000).toString().padStart(4, '0')
    
    // 获取当前时间
    const currentDate = new Date().toISOString().split('T')[0]
    
    // 1) 更新订单主表状态
    const orderPayload = {
      id: refundTargetRow.id,
      orderStatus: '已退款',
      transactionStatus: '退款成功'
    }
    
    await updateOrdermanagement(orderPayload)
    console.log('订单状态更新成功')
    
    // 2) 创建退款记录到数据库
    const refundRecordPayload = {
      refundNo: refundNo,
      orderNo: refundTargetRow.orderNo,
      refundAmount: refundTargetRow.orderAmount,
      applicant: refundTargetRow.orderUserId, // 从订单表的order_user_id字段获取下单人用户ID
      applicationTime: currentDate,
      refundTime: currentDate,
      refundOrderStatus: '已退款',
      refundStatus: '退款成功',
      refundReason: refundForm.value.reason,
      refundChannel: '原路返回', // 退款渠道统一为"原路返回"
      refundMethod: '返回预存款余额' // 退款方式为"返回预存款余额"
    }
    
    console.log('退款记录数据:', refundRecordPayload)
    console.log('申请人ID (orderUserId):', refundRecordPayload.applicant)
    console.log('退款渠道:', refundRecordPayload.refundChannel)
    console.log('退款方式:', refundRecordPayload.refundMethod)
    console.log('订单完整数据:', refundTargetRow)
    
    await addRecordservice(refundRecordPayload)
    console.log('退款记录创建成功')
    
    // 3) 使用老人外键ID查询余额信息
    const elderlyId = refundTargetRow.elderlyId  // 从订单表获取老人外键ID
    const refundAmount = parseFloat(refundTargetRow.orderAmount || 0)
    
    console.log('==== 开始更新老人余额 ====')
    console.log('老人ID:', elderlyId)
    console.log('退款金额:', refundAmount)
    
    // 通过老人ID查询余额记录
    const balanceQuery = {
      elderlyId: elderlyId
    }
    const balanceResponse = await listBalance(balanceQuery)
    console.log('余额查询响应:', balanceResponse)
    
    if (balanceResponse.rows && balanceResponse.rows.length > 0) {
      const elderlyBalance = balanceResponse.rows[0]
      console.log('找到老人余额记录:', elderlyBalance)
      
      // 计算新的预交款余额：当前预交款余额 + 退款金额
      const currentPrepaymentBalance = parseFloat(elderlyBalance.prepaymentBalance || 0)
      const newPrepaymentBalance = currentPrepaymentBalance + refundAmount
      
      console.log('当前预交款余额 (prepayment_balance):', currentPrepaymentBalance)
      console.log('退款金额:', refundAmount)
      console.log('新预交款余额:', newPrepaymentBalance)
      
      // 更新余额表中的预交款余额字段
      const balanceUpdatePayload = {
        id: elderlyBalance.id,
        elderlyId: elderlyId,
        prepaymentBalance: newPrepaymentBalance  // 使用正确的字段名
      }
      
      console.log('准备更新余额，payload:', balanceUpdatePayload)
      const updateResult = await updateBalance(balanceUpdatePayload)
      console.log('余额更新结果:', updateResult)
      console.log('✅ 老人预交款余额更新成功！')
      console.log('   老人ID:', elderlyId)
      console.log('   老人姓名:', refundTargetRow.elderly?.name)
      console.log('   原预交款余额:', currentPrepaymentBalance)
      console.log('   退款金额:', refundAmount)
      console.log('   新预交款余额:', newPrepaymentBalance)
      console.log('==== 余额更新完成 ====')
    } else {
      console.error('❌ 未找到老人ID为', elderlyId, '的余额记录')
      console.log('请检查余额表中是否存在该老人的记录')
    }
    
    refundDialogVisible.value = false
    getList()
    
    // 直接跳转到退款管理页面
    proxy.$router.push('/Finance/ddgl/recordservice')
    
  } catch (error) {
    console.error('退款失败:', error)
    proxy.$modal.msgError('退款失败：' + (error.message || '请稍后重试'))
  }
}

getList()

// 根据状态控制按钮
function canCancel(status) {
  // 待支付可点击，其余禁用
  return status === '待支付'
}

function canRefund(status) {
  // 待执行、已执行可点击；待支付/已完成/已关闭/已退款 不可点击
  return status === '待执行' || status === '已执行'
}
</script>

<style scoped>
.status-filter {
  margin-bottom: 20px;
  padding: 15px 0;
}

.status-filter /deep/ .el-radio-button__inner {
  padding: 10px 20px;
  font-size: 15px;
  height: auto;
  line-height: 1.5;
}

.status-filter /deep/ .el-radio-button:first-child .el-radio-button__inner {
  border-radius: 4px 0 0 4px;
}

.status-filter /deep/ .el-radio-button:last-child .el-radio-button__inner {
  border-radius: 0 4px 4px 0;
}
</style>
